package com.songshan.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.songshan.bean.User;
import com.songshan.bean.UserRole;
import com.songshan.dao.UserMapper;
import com.songshan.dao.UserRoleMapper;
import com.songshan.dto.PageParameter;
import com.songshan.dto.UserDto;
import com.songshan.exception.BusinessException;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UserManageService {

  private Logger log = LoggerFactory.getLogger(this.getClass());

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private UserRoleMapper userRoleMapper;

  @Value("${resource.path}")
  private String resourcePath;

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void addUser(MultipartFile file, UserDto userDto) throws BusinessException {
    User existsUser = userMapper.selectUserByCode(userDto.getUsername());
    if (existsUser != null) {
      throw new BusinessException(500, userDto.getUsername() + "账号已被注册！");
    }
    User user = new User();
    BeanUtil.copyProperties(userDto,user);
    if (file != null) {
      user.setPhoto(uploadPhoto(file, user.getUsername()));
    }
    user.setStatus(1);
    user.setCreateTime(new Date());
    userMapper.insertUser(user);
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void modUser(MultipartFile file, UserDto userDto) throws BusinessException {
    if (userDto.getId() == null) {
      return;
    }
    User user = userMapper.selectUserById(userDto.getId());
    BeanUtil.copyProperties(userDto, user);
    User existsUser = userMapper.selectUserByCode(user.getUsername());
    if (existsUser != null && !existsUser.getId().equals(user.getId())) {
      throw new BusinessException(500, user.getUsername() + "账号已被注册！");
    }
    if (file != null) {
      user.setPhoto(uploadPhoto(file, user.getUsername()));
    }
    user.setModifyTime(new Date());
    userMapper.updateUser(user);
  }

  private String uploadPhoto(MultipartFile multipartFile, String username)
      throws BusinessException {
    try {
      String type = multipartFile.getOriginalFilename()
          .substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
      String path = "photo/" + username + "." + type;
      File file = new File(resourcePath + path);
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }
      multipartFile.transferTo(file);
      return "/"+path;
    } catch (IOException io) {
      throw new BusinessException(500, "头像上传失败：" + io.getMessage());
    }
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void delUser(Integer id) throws BusinessException{
    User user = userMapper.selectUserById(id);
    if(user==null){
      throw new BusinessException(500, "未找到对应用户：" + id);
    }
    if(user.getPhoto()!=null&&!user.getPhoto().isEmpty()){
      deleteFile(new File(resourcePath+user.getPhoto().substring(1)));
    }
    userRoleMapper.deleteUserRoleByUserId(id);
    userMapper.deleteUserById(id);
  }

  private void deleteFile(File file){
    if(file==null||!file.exists()){
      return;
    }
    if(file.isDirectory()){
      File[] childs = file.listFiles();
      if(childs!=null&&childs.length>0){
        for (File child:childs){
          deleteFile(child);
        }
      }
    }else if(file.isFile()){
      file.delete();
    }
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void userStatus(Integer id,Integer status) throws BusinessException{
    User user = userMapper.selectUserById(id);
    if(user==null){
      throw new BusinessException(500, "未找到对应用户：" + id);
    }
    user.setStatus(status);
    user.setModifyTime(new Date());
    userMapper.updateUser(user);
  }

  public User queryUserDetail(Integer id) {
    if (id == null) {
      return null;
    }
    return userMapper.selectUserById(id);
  }

  public Map<String, Object> queryUserWithPage(PageParameter queryParameter) {
    Map<String, Object> result = new HashMap<>();
    Page<User> page = null;
    try {
      page = PageHelper.startPage(queryParameter.getPageNumber(), queryParameter.getPageSize());
      List<User> list = userMapper.selectUserWithPage(queryParameter.getParams());
      result.put("total", page.getTotal());
      result.put("rows", list);
    } finally {
      if (page != null) {
        page.close();
      }
    }
    return result;
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void addRole(Map<String, Object> param) throws BusinessException {
    Integer userId = (Integer) param.get("userId");
    if (userId == null) {
      throw new BusinessException(500,"请选择需要授权的用户！");
    }
    userRoleMapper.deleteUserRoleByUserId(userId);
    List<Integer> roleIds = (List<Integer>) param.get("roleIds");
    if (roleIds == null || roleIds.isEmpty()) {
      return;
    }
    Date date = new Date();
    for (Integer roleId : roleIds) {
      UserRole userRole = new UserRole();
      userRole.setRoleId(roleId);
      userRole.setUserId(userId);
      userRole.setCreateTime(date);
      userRoleMapper.insertUserRole(userRole);
    }
  }
}
